package cn.xyfmzmy.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class NettyServer {

    public static void main(String[] args) {
        // 模拟数据集，存储每个Channel里的消息
        Map<Channel, List<String>> db = new ConcurrentHashMap<>();

        // Bootstrap 对各种组件进行整合与管理
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(new NioEventLoopGroup(), new NioEventLoopGroup()) // 管理EventLoop，第一个是BossEventLoop(处理accpet事件),第二个是WorkEventLoop(处理read/write事件)
                .channel(NioServerSocketChannel.class)      // 设置通道类型，这里是服务器，所以是 ServerSocketChannel
                .childHandler(new ChannelInitializer<SocketChannel>() {   // 给每一个子链接(SocketChannel)设置初始化的Handler
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 添加Handler
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024))      // 行读取，根据\n分割
                                .addLast(new StringDecoder())
                                .addLast(new StringEncoder())
                                .addLast(new ResponseHandler())
                                .addLast(new DbHandler(db));
                    }
                });
        ChannelFuture bindFuture = serverBootstrap.bind(8080);
        bindFuture.addListener( future ->{
            if(future.isSuccess()){
                System.out.println("服务器成功监听端口"+8080);
            }else{
                System.out.println("服务器监听端口失败");
            }
        });
    }

    // 将Handler抽象出来
    static class ResponseHandler extends SimpleChannelInboundHandler<String> {
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println(msg);
            String message = msg + " world\n";
            // ctx.writeAndFlush(message)是直接往回走，ctx.channel().writeAndFlush(message)是从尾部往回走
            ctx.channel().writeAndFlush(message);       // 写回客户端。
            ctx.fireChannelRead(msg);                   // 注意，需要把消息传给下一个handler
        }

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println(ctx.channel() + "注册了");
            ctx.fireChannelRegistered();            // 事件也有传播顺序，需要把事件传播出去，不然只会打印1次
        }
    }


    static class DbHandler extends SimpleChannelInboundHandler<String> {

        private Map<Channel,List<String>> db;

        public DbHandler(Map<Channel, List<String>> db) {
            this.db = db;
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            List<String> messageList = db.computeIfAbsent(ctx.channel(), k -> new ArrayList<>());
            messageList.add(msg);
        }

        @Override
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println(ctx.channel() + "注册了");
        }

        @Override
        public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
            System.out.println(ctx.channel() + "解除注册了");
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(ctx.channel() + "可以使用了");
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            // channle不活跃的监听函数
            List<String> strings = db.get(ctx.channel());
            System.out.println(strings);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            // 异常处理的
            super.exceptionCaught(ctx, cause);
        }
    }
}
